"""
数据库基础配置
"""
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config.settings import settings

# 数据库连接URL
DATABASE_URL = f"mysql+pymysql://{settings.DB_USER}:{settings.DB_PASSWORD}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}"

# 创建数据库引擎
engine = create_engine(
    DATABASE_URL,
    pool_pre_ping=True,  # 连接前检测连接是否可用
    pool_size=10,  # 连接池大小
    max_overflow=20,  # 超出连接池大小的额外连接数
    echo=False  # 是否打印SQL语句（调试时可设为True）
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 声明式基类
Base = declarative_base()


def get_db():
    """
    获取数据库会话，用于依赖注入
    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

